package io.xiaojl.xj2ee.common.kit.security.impl;

import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

import io.xiaojl.xj2ee.common.kit.security.HexUtil;
import io.xiaojl.xj2ee.common.kit.security.IEncrypt;


/**
 * <p>Title: RSAEncrypt</p>  
 *
 * <p>Description: 非对称加密算法: RSA加密</p>  
 *
 * @author jilong.xiao  
 * @date 2018年5月23日
 */
public class RSAEncrypt implements IEncrypt {
    private PublicKey publicKey;
    private PrivateKey privateKey;
//    private String publicKeyString;
//    private String privateKeyString;
    
    // 加解密类
    private Cipher cipher;

    public RSAEncrypt(PublicKey publicKey, PrivateKey privateKey) {
        this.publicKey = publicKey;
        this.privateKey = privateKey;
    }

    /**
     * 加密
     */
    @Override
    public String encrypt(String string) {
        String afterEncrypt = null;
        try {

            // 加解密类
            cipher = Cipher.getInstance("RSA");// Cipher.getInstance("RSA/ECB/PKCS1Padding");
            // 明文
            byte[] plainText = string.getBytes();
            // 公钥加密
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] enBytes = cipher.doFinal(plainText); 
            afterEncrypt = HexUtil.bytes2Hex(enBytes);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return afterEncrypt;
    }

    /**
     * 解密
     */
    @Override
    public String decrypt(String string) {
        byte[] bytes = HexUtil.hex2Bytes(string);
        String afterDecrypt = null;
        // 加解密类
        try {
            cipher = Cipher.getInstance("RSA");// Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] deBytes = cipher.doFinal(bytes);
//            publicKeyString = getKeyString(publicKey);
//            privateKeyString = getKeyString(privateKey);
            afterDecrypt = new String(deBytes);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return afterDecrypt;
    }

    /**
     * 得到密钥字符串（经过base64编码）
     * 
     * @return
     */
    public static String getKeyString(Key key) throws Exception {
        byte[] keyBytes = key.getEncoded();
        return Base64.encodeBase64String(keyBytes);

    }
}